package com.ruoyi.system.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.CrmStudent;
import com.ruoyi.system.domain.WorkWeixinToken;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWorkWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class WorkWeixinServiceImpl implements IWorkWeixinService {


    @Autowired
    private ISysConfigService configService;

    @Resource
    private ISysUserService userService;

    @Override
    public String getTokenFromWeixin() throws JsonProcessingException {

        String accessToken = null;
        RestTemplate restTemplate = new RestTemplate();

        Map<String, String> params = new HashMap<>();

        params.put("corpid", configService.selectConfigByKey("sys.workWeixin.id"));
        params.put("corpsecret", configService.selectConfigByKey("sys.workWeixin.appSecret"));

        ResponseEntity<String> tokenRes = restTemplate.getForEntity(WORK_WEI_XIN_DOMAIN + "/gettoken?corpid={corpid}&corpsecret={corpsecret}", String.class,params);

        if(tokenRes.getStatusCode() == HttpStatus.OK) {
            ObjectMapper mapper = new ObjectMapper();
                WorkWeixinToken token = mapper.readValue(tokenRes.getBody(), WorkWeixinToken.class);

                if(token.getErrcode() == 0 && "ok".equalsIgnoreCase(token.getErrmsg())) {

                    accessToken = token.getAccess_token();

                    CacheUtils.put(WORK_WEI_XIN_TOKEN_CACHE_NAME, configService.selectConfigByKey("sys.workWeixin.id"), accessToken);
                }
        }

        return accessToken;

    }

    @Override
    public String getTokenFromCache() {
        Object token = CacheUtils.get(WORK_WEI_XIN_TOKEN_CACHE_NAME, configService.selectConfigByKey("sys.workWeixin.id"));
        return token == null ? null : token.toString();
    }

    @Override
    public String getToken() throws JsonProcessingException {

        String accessToken = getTokenFromCache();

        if(StringUtils.isEmpty(accessToken)) {
            accessToken = getTokenFromWeixin();
        }

        return accessToken;
    }

//    @Override
//    public Boolean sendStudentMessage(Long userId) throws JsonProcessingException {
//
//        Boolean sendSuccess = Boolean.FALSE;
//
//        String accessToken = getToken();
//        if(StringUtils.isNotEmpty(accessToken)) {
//
//            SysUser user = userService.selectUserById(userId);
//
//            if("0".equalsIgnoreCase(user.getSaleStatus()) && StringUtils.isNotEmpty(user.getWorkWeixin())) {
//                RestTemplate restTemplate = new RestTemplate();
//
//                Map<String, String> params = new HashMap<>();
//                params.put("accessToken", accessToken);
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.setContentType(MediaType.APPLICATION_JSON);
//
//                String jsonBody = "{\"touser\":\""+ user.getWorkWeixin() +"\"," +
//                        "\"msgtype\":\"text\"," +
//                        "\"agentid\":1000002," +
////                        "\"text\":{\"content\":\"你的客户已分配，请登录学员管理系统前往领取。\\n ---- <a href=\\\"http://stu.zcxzedu.com/crm/salesman/student\\\">点击领取</a> ----\"}," +
//                        "\"text\":{\"content\":\"你的客户已分配，请登录学员管理系统查看。\\n学员信息：\\n ---- <a href=\\\"http://stu.zcxzedu.com/crm/salesman/student\\\">点击领取</a> ----\"}," +
//                        "\"safe\":0," +
//                        "\"enable_id_trans\":0," +
//                        "\"enable_duplicate_check\":0}";
//
//                HttpEntity<String> request = new HttpEntity<>(jsonBody, headers);
//
//                ResponseEntity<String> sendMsgRes = restTemplate.postForEntity(WORK_WEI_XIN_DOMAIN +"/message/send?access_token={accessToken}", request, String.class, params);
//
//                if(sendMsgRes.getStatusCode() == HttpStatus.OK) {
//                    ObjectMapper mapper = new ObjectMapper();
//
//                    JsonNode resNode = mapper.readValue(sendMsgRes.getBody(), JsonNode.class);
//
//                    if(resNode.get("errcode").asInt() == 0 && "ok".equalsIgnoreCase(resNode.get("errmsg").asText())) {
//                        sendSuccess = Boolean.TRUE;
//                    }
//                }
//            }
//        }
//        return sendSuccess;
//    }

//    @Override
//    public Boolean sendStudentMessage(Long userId, String message) throws JsonProcessingException {
//        Boolean sendSuccess = Boolean.FALSE;
//
//        String agentId = configService.selectConfigByKey("sys.workWeixin.appAgentId");
//
//        String accessToken = getToken();
//        if(StringUtils.isNotEmpty(accessToken)) {
//
//            SysUser user = userService.selectUserById(userId);
//
//            if("0".equalsIgnoreCase(user.getSaleStatus()) && StringUtils.isNotEmpty(user.getWorkWeixin()) && StringUtils.isNotEmpty(agentId)) {
//
//                RestTemplate restTemplate = new RestTemplate();
//
//                Map<String, String> params = new HashMap<>();
//                params.put("accessToken", accessToken);
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.setContentType(MediaType.APPLICATION_JSON);
//
//                String jsonBody = "{\"touser\":\""+ user.getWorkWeixin() +"\"," +
//                        "\"msgtype\":\"text\"," +
//                        "\"agentid\":"+ agentId +"," +
//                        "\"text\":{\"content\":\"您的学员已分配，请登录学员管理系统查看。\\n学员信息：“"+ message +"”\\n ---- <a href=\\\"http://stu.zcxzedu.com/crm/salesman/student\\\">点击查看</a> ----\"}," +
//                        "\"safe\":0," +
//                        "\"enable_id_trans\":0," +
//                        "\"enable_duplicate_check\":0}";
//
//                HttpEntity<String> request = new HttpEntity<>(jsonBody, headers);
//
//                ResponseEntity<String> sendMsgRes = restTemplate.postForEntity(WORK_WEI_XIN_DOMAIN +"/message/send?access_token={accessToken}", request, String.class, params);
//
//                if(sendMsgRes.getStatusCode() == HttpStatus.OK) {
//                    ObjectMapper mapper = new ObjectMapper();
//
//                    JsonNode resNode = mapper.readValue(sendMsgRes.getBody(), JsonNode.class);
//
//                    if(resNode.get("errcode").asInt() == 0 && "ok".equalsIgnoreCase(resNode.get("errmsg").asText())) {
//                        sendSuccess = Boolean.TRUE;
//                    }
//                }
//            }
//        }
//        return sendSuccess;
//    }

    @Override
    public Boolean sendStudentMessage(CrmStudent student) throws JsonProcessingException {
        Boolean sendSuccess = Boolean.FALSE;

        String agentId = configService.selectConfigByKey("sys.workWeixin.appAgentId");

        String accessToken = getToken();
        if(StringUtils.isNotEmpty(accessToken)) {

            SysUser user = userService.selectUserById(student.getSalesmanId());

            if("0".equalsIgnoreCase(user.getSaleStatus()) && StringUtils.isNotEmpty(user.getWorkWeixin()) && StringUtils.isNotEmpty(agentId)) {

                RestTemplate restTemplate = new RestTemplate();

                Map<String, String> params = new HashMap<>();
                params.put("accessToken", accessToken);

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                StringBuilder bodyBuilder = new StringBuilder();

                bodyBuilder.append("{\"touser\":\""+ user.getWorkWeixin() +"\"," +
                        "\"msgtype\":\"text\"," +
                        "\"agentid\":"+ agentId +"," +
                        "\"text\":{\"content\":\"您的学员已分配，请登录学员管理系统查看。");
                if(StringUtils.isNotEmpty(student.getStuName())) {
                    bodyBuilder.append("\\n姓名：" + student.getStuName());
                }
                if(StringUtils.isNotEmpty(student.getStuMobile())) {
                    bodyBuilder.append("\\n电话：" + student.getStuMobile());
                }
                if(StringUtils.isNotEmpty(student.getStuWechat())) {
                    bodyBuilder.append("\\n微信：" + student.getStuWechat());
                }

                bodyBuilder.append("\\n需求：" + student.getStuDamand());

                if(StringUtils.isNotEmpty(student.getNote())) {
                    bodyBuilder.append("\\n备注：" + student.getNote());
                }
                bodyBuilder.append("\\n ---- <a href=\\\"http://stu.zcxzedu.com/crm/salesman/student\\\">点击查看</a> ----\"}," +
                        "\"safe\":0," +
                        "\"enable_id_trans\":0," +
                        "\"enable_duplicate_check\":0}");

                HttpEntity<String> request = new HttpEntity<>(bodyBuilder.toString(), headers);

                ResponseEntity<String> sendMsgRes = restTemplate.postForEntity(WORK_WEI_XIN_DOMAIN +"/message/send?access_token={accessToken}", request, String.class, params);

                if(sendMsgRes.getStatusCode() == HttpStatus.OK) {
                    ObjectMapper mapper = new ObjectMapper();

                    JsonNode resNode = mapper.readValue(sendMsgRes.getBody(), JsonNode.class);

                    if(resNode.get("errcode").asInt() == 0 && "ok".equalsIgnoreCase(resNode.get("errmsg").asText())) {
                        sendSuccess = Boolean.TRUE;
                    }
                }
            }
        }
        return sendSuccess;
    }
}
